package com.shujia.flink.source

import java.util.Properties
import java.util.regex.Pattern

import org.apache.flink.api.common.serialization.SimpleStringSchema
import org.apache.flink.streaming.api.scala._
import org.apache.flink.streaming.connectors.kafka.{FlinkKafkaConsumer, FlinkKafkaProducer}
import org.apache.kafka.clients.consumer.ConsumerConfig
import scala.collection.JavaConverters._

object Demo5KafkaSource {
  def main(args: Array[String]): Unit = {

    val env: StreamExecutionEnvironment = StreamExecutionEnvironment.getExecutionEnvironment

    val properties: Properties = new Properties()
    properties.setProperty("bootstrap.servers", "master:9092,node1:9092,node2:9092")
    properties.setProperty("group.id", "test")
    properties.setProperty("flink.partition-discovery.interval-millis", "100")

    //创建kafkasource
    val kafkaConsumer: FlinkKafkaConsumer[String] = new FlinkKafkaConsumer[String](
      "topic",
      new SimpleStringSchema(),
      properties)


    //    kafkaConsumer.setStartFromEarliest() // 尽可能从最早的记录开始
    kafkaConsumer.setStartFromLatest() // 从最新的记录开始
    //    kafkaConsumer.setStartFromTimestamp(...)  // 从指定的时间开始（毫秒）
    //    kafkaConsumer.setStartFromGroupOffsets()  // 默认的方法

    val kafkaStream: DataStream[String] = env.addSource(kafkaConsumer)

    kafkaStream.print()

    val flterDS: DataStream[String] = kafkaStream.filter(line => line.equals("java"))


    //kafakasink
    val myProducer: FlinkKafkaProducer[String] = new FlinkKafkaProducer[String](
      "master:9092,node1:9092,node2:9092", // broker 列表
      "filter-topic", // 目标 topic
      new SimpleStringSchema) // 序列化 schema


    //将数据保存到kafka中
    flterDS.addSink(myProducer)


    env.execute()

  }
}
